/*
 * Created on 21.10.2003
 * Local Projects Database
 * Mihai Postelnicu (mihai@ro-gateway.org)
 * (c) 2003 by eRomania Gateway
 */
package ro.gateway.aida.utils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;



/**
 * @author Mihai Postelnicu
 *  Implements a sortable ArrayList
 *  e-mail (mihai@ro-gateway.org)
 * (c) 2003 by eRomania Gateway
 */
public class SortedList extends ArrayList
{
      protected Comparator comparator;

      public SortedList( Comparator c )
      {
            this.comparator = c;
      }

      public SortedList()
      {
            this.comparator = null;
      }

      public SortedList( Comparator c, List l )
      {
            this.comparator = c;

            if ( l != null )
            {
                  Iterator i = l.iterator();

                  while ( i.hasNext() )
                        add( i.next() );
            }
      }

      public boolean add( Object o )
      {
            if ( comparator == null )
                  super.add( o );
            else
            {
                  for ( int x = 0; x < size(); x++ )
                  {
                        Object element = get( x );

                        if ( comparator.compare( element, o ) >= 0 )
                        {
                              add( x, o );

                              return true;
                        }
                  }

                  super.add( o );
            }

            return true;
      }

      /**
       * @return
       */
      public Comparator getComparator()
      {
            return comparator;
      }

      protected void reorder()
      {
            SortedList t = new SortedList( comparator );
            Iterator i = iterator();
            while ( i.hasNext() )
            {
                  t.add( i.next() );
            }
            this.clear();
            //might not be optimized
            //TODO: optimize this!
            this.addAll( t );
      }

      /**
       * @param comparator
       */
      public void setComparator( Comparator comparator )
      {
            this.comparator = comparator;
            reorder();
      }

}
